<template>
  <view @touchstart="touchStart" @touchend="touchEnd"> <!-- 添加触摸事件 -->
    <u-navbar :is-back="true" title="答题"></u-navbar>
    <view class="content-area">
      <u-tabs-swiper ref="tabsSwiper" :list="currentTab === '材料' ? materialsList : questionsList" 
                      :current="currentMaterialIndex" @change="onTabChange" 
                      :is-scroll="false" active-color="#2979ff" 
                      inactive-color="#606266" font-size="30" bar-height="6" bar-width="40"></u-tabs-swiper>
      <div v-if="currentTab === '材料'">
        <u-parse :html="currentQuestion.materials[currentMaterialIndex]" style="font-size: 13px;" 
                 :selectable="true" :lazy-load="true"></u-parse>
      </div>
      <div v-if="currentTab === '问题'">
        <u-parse :html="currentQuestion.content[currentMaterialIndex]" style="font-size: 13px;" 
                 :selectable="true" :lazy-load="true"></u-parse>
      </div>
      <u-toast ref="uToast" />
    </view>
    <view class="space"></view>
    <view style="position: fixed; bottom: 0px; width: 750rpx; display: flex; flex-direction: column; 
          border-top: 1px solid #ccc; padding-top: 1px; padding-bottom: 5px; background-color: white; z-index: 1019;">
      <div class="tabs-input-container">
        <div class="tabs-and-input-row" style="display: flex; align-items: center; justify-content: space-between; width: 100%;">
          <div class="tabs-container">
            <div class="tab" :class="{ active: currentTab === '材料' }" @click="selectTab('材料')">材料</div>
            <div class="tab" :class="{ active: currentTab === '问题' }" @click="selectTab('问题')">问题</div>
          </div>
          <div class="input-container">
            <input type="text" placeholder="请输入答案..." v-model="inputText" :disabled="currentTab === '材料'" 
                   @focus="showInputDialog = true" @click="handleInputClick" />
          </div>
          <div class="next-button-container" style="margin-left: auto;">
            <u-button shape="square" :custom-style="{ height: '30px', width: '180rpx' }" @click="submitAnswers" 
                      :disabled="isSubmitted">交卷</u-button>
          </div>
        </div>
      </div>
      <!-- 输入对话框 -->
      <u-popup v-model="showInputDialog" mode="bottom" border-radius="10" height="800rpx" @close="handlePopupClose">
        <view class="popup-content">
          <view class="dialog-header">
            <span class="cancel" @click="showInputDialog = false">✖</span>
            <span class="dialog-title">{{ dialogTitle }}</span>
            <span class="save" @click="clearInput">清空</span>
          </view>
          <textarea v-model="inputText" class="input-area" :disabled="isSubmitted" @input="updateCharacterCount" 
                    maxlength="2000"></textarea>
          <div class="character-count">{{ characterCount }}/2000</div>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
import UToast from "@/uview-ui/components/u-toast/u-toast.vue"
import UParse from "@/uview-ui/components/u-parse/u-parse.vue"
import { allSlquestions } from '@/api/business/slquestion'
import { addCorrect } from '@/api/business/correct'
import { getUserProfile } from '@/api/system/user'
import { getSlpaper } from '@/api/business/slpaper'
import { showConfirm, toast } from '@/utils/common'

export default {
  components: {
    UToast,
    UParse
  },
  data() {
    return {
      currentTab: '材料',
      showInputDialog: false,
      inputText: '',
      characterCount: 0,
      dialogTitle: '问题一',
      currentQuestion: {
        id: null,
        materials: [],
        content: [],
      },
      currentMaterialIndex: 0,
      materialsList: [],
      questionsList: [],
      user_answers: [],
      lastInputText: '',
      paperType: null,
      isSubmitted: false,
      startX: 0, // 触摸开始的X坐标
    };
  },
  onLoad(options) {
    const { paper_type, id, type } = options;
    this.paperType = paper_type;

    if (paper_type && id) {
      this.fetchPaper(id);
    } else if (type) {
      this.fetchQuestions(type);
    }
  },
  methods: {
    touchStart(event) {
      this.startX = event.touches[0].clientX; // 记录触摸开始的X坐标
    },
    touchEnd(event) {
      const endX = event.changedTouches[0].clientX; // 触摸结束的X坐标
      const distance = this.startX - endX; // 计算滑动的距离

      if (distance > 50) {
        // 向左滑动，进入下一tab
        this.selectNextTab();
      } else if (distance < -50) {
        // 向右滑动，返回上一tab
        this.selectPreviousTab();
      }
    },
    selectNextTab() {
      if (this.currentTab === '材料' && this.currentMaterialIndex < this.currentQuestion.materials.length - 1) {
        this.currentMaterialIndex++;
        this.updateDialogTitle();
      } else if (this.currentTab === '问题' && this.currentMaterialIndex < this.currentQuestion.content.length - 1) {
        this.currentMaterialIndex++;
        this.updateDialogTitle();
      }
    },
    selectPreviousTab() {
      if (this.currentTab === '材料' && this.currentMaterialIndex > 0) {
        this.currentMaterialIndex--;
        this.updateDialogTitle();
      } else if (this.currentTab === '问题' && this.currentMaterialIndex > 0) {
        this.currentMaterialIndex--;
        this.updateDialogTitle();
      }
    },
    selectTab(tab) {
      this.currentTab = tab;
      this.currentMaterialIndex = 0;
      this.updateDialogTitle();
      if (tab === '材料') {
        this.materialsList = this.currentQuestion.materials.map((material, index) => ({
          name: `材料${this.toChineseNumber(index + 1)}`,
        }));
        this.inputText = this.lastInputText;
      } else if (tab === '问题') {
        this.questionsList = this.currentQuestion.content.map((content, index) => ({
          name: `问题${this.toChineseNumber(index + 1)}`,
        }));
      }
    },
    updateDialogTitle() {
      if (this.currentTab === '问题') {
        this.dialogTitle = `问题${this.toChineseNumber(this.currentMaterialIndex + 1)}`;
      } else {
        if (!this.dialogTitle.startsWith('问题')) {
          this.dialogTitle = '问题一';
        }
      }
    },
    clearInput() {
      if (this.isSubmitted == false) {
        this.inputText = '';
        this.characterCount = 0;
      }
    },
    updateCharacterCount() {
      this.characterCount = this.inputText.length;
    },
    fetchPaper(id) {
      getSlpaper(id).then(response => {
        if (response && response.code === 200 && response.data) {
          this.currentQuestion = response.data;
          this.currentQuestion.materials = JSON.parse(this.currentQuestion.materials || '[]');
          this.currentQuestion.content = JSON.parse(this.currentQuestion.content || '[]');
          this.materialsList = this.currentQuestion.materials.map((material, index) => ({
            name: `材料${this.toChineseNumber(index + 1)}`,
          }));
          this.questionsList = this.currentQuestion.content.map((content, index) => ({
            name: `问题${this.toChineseNumber(index + 1)}`,
          }));
          this.user_answers = new Array(this.currentQuestion.content.length).fill(null);
        } else {
          console.error('No paper found or invalid response structure');
        }
      }).catch(error => {
        console.error('Error fetching paper:', error);
      });
    },
    fetchQuestions(type) {
      allSlquestions({}).then(response => {
        if (response && response.code === 200 && response.data && response.data.length > 0) {
          const filteredQuestions = response.data.filter(question => question.type === type);
          if (filteredQuestions.length > 0) {
            const randomIndex = Math.floor(Math.random() * filteredQuestions.length);
            this.currentQuestion = filteredQuestions[randomIndex];
            this.currentQuestion.materials = JSON.parse(this.currentQuestion.materials || '[]');
            this.currentQuestion.content = JSON.parse(this.currentQuestion.content || '[]');
            this.materialsList = this.currentQuestion.materials.map((material, index) => ({
              name: `材料${this.toChineseNumber(index + 1)}`,
            }));
            this.questionsList = this.currentQuestion.content.map((content, index) => ({
              name: `问题${this.toChineseNumber(index + 1)}`,
            }));
            this.user_answers = new Array(this.currentQuestion.content.length).fill(null);
          }
        } else {
          console.error('No questions found or invalid response structure');
        }
      }).catch(error => {
        console.error('Error fetching questions:', error);
      });
    },
    onTabChange(index) {
      this.currentMaterialIndex = index;
      this.updateDialogTitle();
      this.inputText = this.user_answers[index] || '';
      this.updateCharacterCount(); // 确保更新字符统计
      if (this.currentTab === '问题') {
        this.lastInputText = this.inputText;
      }
    },
    toChineseNumber(num) {
      const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return chineseNumbers[num] || '';
    },
    submitAnswers() {
      showConfirm('您确定要提交吗？').then(res => {
        if (res.confirm) {
          this.confirmSubmit(); // 用户确认后调用提交方法
        }
      });
    },
    confirmSubmit() {
      // 保存当前答案
      this.user_answers[this.currentMaterialIndex] = this.inputText;
      getUserProfile().then(response => {
        if (response && response.code === 200) {
          const userId = response.data.userId;
          const dttime = new Date().toISOString();
          const correctData = {
            user_id: userId,
            question_id: this.currentQuestion.id,
            paper_id: this.currentQuestion.id,
            dttime: dttime,
            user_answers: JSON.stringify(this.user_answers),
            status: '0',
            type: this.currentQuestion.type || null,
          };
          /* 根据是否存在 paperType，来决定是套卷练习还是专项练习 */
          if (this.paperType) {  // 如果是套卷练习
            delete correctData.question_id;  // 删除 question_id
          } else {  // 如果是专项练习
            delete correctData.paper_id;  // 删除 paper_id
          }
          addCorrect(correctData).then(response => {
            if (response && response.code === 200) {
              this.showToast('提交成功，请耐心等待批改', 'success');
              this.isSubmitted = true;
            } else {
              console.error('Failed to submit answers: ', response.msg || 'Unknown error');
            }
          }).catch(error => {
            console.error('Error submitting answers:', error);
          });
        } else {
          console.error('Failed to get user profile');
        }
      }).catch(error => {
        console.error('Error fetching user profile:', error);
      });
    },
    handlePopupClose() {
      this.user_answers[this.currentMaterialIndex] = this.inputText;
      if (this.currentTab === '问题') {
        this.lastInputText = this.inputText;
      }
    },
    handleInputClick() {
      if (this.currentTab === '材料') {
        this.showToast('请先点击问题再输入文本哦', 'info');
      }
    },
    showToast(message, type) {
      this.$refs.uToast.show({
        title: message,
        type: 'primary',
        position: 'bottom',
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.space {
  padding-bottom: 15%;
}

.content-area {
  padding: 10px;
  padding-bottom: 3%;
  background-color: #ffffff;
  border: 1px solid #ccc;
  border-radius: 10px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tabs-input-container {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  margin-top: 10px;
}

.tabs-and-input-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 10px;
}

.tabs-container {
  display: flex;
  background-color: #e0f7fa;
  border-radius: 20px;
  overflow: hidden;
  width: 180rpx;
  margin-right: 20rpx;
  height: 60rpx;
  justify-content: center;
}

.tab {
  flex: 1;
  padding: 5px;
  text-align: center;
  color: black;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.tab.active {
  background-color: #1976d2;
  color: white;
}

.input-container {
  display: flex;
  align-items: center;
  height: 60rpx;
  width: 300rpx;
}

.input-container input {
  width: 100%;
  padding: 0 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  height: 100%;
}

.next-button-container {
  margin-left: 20rpx;
  display: flex;
  align-items: center;
}

.popup-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding-bottom: 50px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  padding: 7px;
  background-color: white;
}

.cancel,
.save {
  cursor: pointer;
  font-size: 14px;
}

.dialog-title {
  font-weight: bold;
  font-size: 16px;
}

.input-area {
  flex-grow: 1;
  width: 100%;
  margin-top: 10px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  padding: 4px;
  resize: none;
  box-sizing: border-box;
}

.character-count {
  position: absolute;
  bottom: 10px;
  right: 10px;
  color: #666;
  font-size: 15px;
}
</style>
